#!/bin/bash

# DBC Editor VSCode Plugin Build Script
echo "🚀 Building DBC Editor VSCode Plugin..."

# 检查依赖
echo "📦 Installing dependencies..."
npm install

# 编译TypeScript
echo "🔨 Compiling TypeScript..."
if command -v tsc &> /dev/null; then
    tsc -p ./
else
    echo "⚠️  TypeScript compiler not found, using npx..."
    npx tsc -p ./
fi

# 验证编译输出
if [ -d "out" ] && [ -f "out/extension.js" ] && [ -f "out/dbcEditorProvider.js" ]; then
    echo "✅ Compilation successful!"
    echo "📁 Output files:"
    ls -la out/
else
    echo "❌ Compilation failed!"
    exit 1
fi

# 验证媒体文件
echo "🔍 Checking media files..."
if [ -f "media/dbc-editor.js" ] && [ -f "media/dbc-editor.css" ] && [ -f "media/dbc-editor-adapted.js" ]; then
    echo "✅ All media files present!"
else
    echo "❌ Missing media files!"
    exit 1
fi

echo "🎉 Build completed successfully!"
echo ""

# 检查是否要打包
if [ "$1" = "--package" ] || [ "$1" = "-p" ]; then
    echo "📦 Packaging extension..."
    if command -v vsce &> /dev/null; then
        echo "y" | vsce package
        if ls *.vsix 1> /dev/null 2>&1; then
            echo "✅ Extension packaged successfully!"
            echo "📁 Package file:"
            ls -la *.vsix
        else
            echo "❌ Packaging failed!"
            exit 1
        fi
    else
        echo "❌ vsce not found! Please install it with:"
        echo "   sudo npm install -g @vscode/vsce"
        exit 1
    fi
else
    echo "📖 Next steps:"
    echo "1. Open this folder in VSCode"
    echo "2. Press F5 to launch the extension in a new window"
    echo "3. Open example.dbc to test the DBC editor"
    echo ""
    echo "📦 To package the extension:"
    echo "   ./build.sh --package"
    echo "   or manually: vsce package"
fi
echo "" 